﻿using AntdUI;
using System.ComponentModel;
using WorkTool2.Entities;
using WorkTool2.Helpers;
using WorkTool2.Properties;

namespace WorkTool2.CustomForms
{
    public partial class AddDbConn : Window
    {
        public AddDbConn()
        {
            InitializeComponent();
            select_dbType.Items.Clear();
            select_dbType.Items.Add(new SelectItem("MySQL").SetIcon(Resources.MySQL));
            select_dbType.Items.Add(new SelectItem("SQLServer").SetIcon(Resources.SQLServer));
            if (Id == 0)
                select_dbType.SelectedIndex = 0;
        }

        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public int Id { get; set; }

        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public string ConnName
        {
            get { return input_name.Text; }
            set { input_name.Text = value; }
        }

        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public int DbType
        {
            get { return select_dbType.SelectedIndex; }
            set { select_dbType.SelectedIndex = value; }
        }

        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public string IPAddress
        {
            get { return input_ipAddress.Text; }
            set { input_ipAddress.Text = value; }
        }

        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public int Port
        {
            get { return (int)inputNumber_port.Value; }
            set { inputNumber_port.Value = value; }
        }

        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public string DefaultDbName
        {
            get { return input_defaultDbName.Text; }
            set { input_defaultDbName.Text = value; }
        }

        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public string User
        {
            get { return input_user.Text; }
            set { input_user.Text = value; }
        }

        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public string Password
        {
            get { return input_password.Text; }
            set { input_password.Text = value; }
        }

        private async void btn_save_Click(object sender, EventArgs e)
        {
            await Spin.open(this, "正在处理中，请耐心等候...", async config =>
             {
                 try
                 {
                     var verify = Verify();
                     if (!string.IsNullOrEmpty(verify.errorMsg))
                     {
                         AntdUI.Modal.open(new Modal.Config(this, "提醒", verify.errorMsg, TType.Warn)
                         {
                             CancelText = null,
                             OkType = TTypeMini.Warn,
                             OkText = "知道了"
                         });
                         return;
                     }
                     var entity = verify.entity;
                     if (entity.Id > 0)
                     {
                         if (!await SqlSugarHelper.SqliteDb.Queryable<DbConnectionEntity>()
                            .AnyAsync(x => !x.Id.Equals(entity.Id) && x.IPAddress.Equals(entity.IPAddress) && x.Port.Equals(entity.Port) && x.User.Equals(entity.User) && x.Password.Equals(entity.Password)))
                         {
                             if (await SqlSugarHelper.SqliteDb.Updateable(entity).ExecuteCommandAsync() > 0)
                                 DialogResult = DialogResult.OK;
                         }
                     }
                     else
                     {
                         if (!await SqlSugarHelper.SqliteDb.Queryable<DbConnectionEntity>()
                            .AnyAsync(x => x.IPAddress.Equals(entity.IPAddress) && x.Port.Equals(entity.Port) && x.User.Equals(entity.User) && x.Password.Equals(entity.Password)))
                         {
                             if (await SqlSugarHelper.SqliteDb.Insertable(entity).ExecuteReturnIdentityAsync() > 0)
                                 DialogResult = DialogResult.OK;
                         }
                     }
                 }
                 catch (Exception ex)
                 {
                     AntdUI.Modal.open(new Modal.Config(this, "错误", ex.Message, TType.Error)
                     {
                         CancelText = null,
                         OkType = TTypeMini.Error,
                         OkText = "知道了"
                     });
                 }
             });
            if (DialogResult == DialogResult.OK)
                Close();
        }

        private void btn_test_Click(object sender, EventArgs e)
        {
            Spin.open(this, "正在处理中，请耐心等候...", config =>
            {
                try
                {
                    var verify = Verify();
                    if (!string.IsNullOrEmpty(verify.errorMsg))
                    {
                        AntdUI.Modal.open(new Modal.Config(this, "提醒", verify.errorMsg, TType.Warn)
                        {
                            CancelText = null,
                            OkType = TTypeMini.Warn,
                            OkText = "知道了"
                        });
                        return;
                    }
                    var entity = verify.entity;
                    var isSuccess = false;
                    switch ((Entities.DbType)select_dbType.SelectedIndex)
                    {
                        case Entities.DbType.MySQL:
                            new SqlSugarHelper().SqlSugarClient(
                                entity.DbConnection + (string.IsNullOrEmpty(entity.DefaultDbName) ? "" : $"database={entity.DefaultDbName};"),
                                SqlSugar.DbType.MySql,
                                client =>
                                {
                                    isSuccess = client.Ado.IsValidConnection();
                                }
                                );
                            break;

                        case Entities.DbType.SQLServer:
                            new SqlSugarHelper().SqlSugarClient(
                                entity.DbConnection + (string.IsNullOrEmpty(entity.DefaultDbName) ? "" : $"database={entity.DefaultDbName};"),
                                SqlSugar.DbType.SqlServer,
                                client =>
                                {
                                    isSuccess = client.Ado.IsValidConnection();
                                }
                                );
                            break;

                        default:
                            break;
                    }
                    if (isSuccess)
                    {
                        AntdUI.Modal.open(new Modal.Config(this, "提醒", "测试连接成功！", TType.Success)
                        {
                            CancelText = null,
                            OkType = TTypeMini.Success,
                            OkText = "知道了"
                        });
                    }
                    else
                    {
                        AntdUI.Modal.open(new Modal.Config(this, "提醒", "测试连接失败！", TType.Warn)
                        {
                            CancelText = null,
                            OkType = TTypeMini.Warn,
                            OkText = "知道了"
                        });
                    }
                }
                catch (Exception ex)
                {
                    AntdUI.Modal.open(new Modal.Config(this, "连接异常", ex.Message, TType.Error)
                    {
                        CancelText = null,
                        OkType = TTypeMini.Error,
                        OkText = "知道了"
                    });
                }
            });
        }

        private (string errorMsg, DbConnectionEntity? entity) Verify()
        {
            if (string.IsNullOrEmpty(input_name.Text))
                return ("连接名称不能为空！", null);
            if (string.IsNullOrEmpty(input_ipAddress.Text))
                return ("服务器地址不能为空！", null);
            if (inputNumber_port.Value <= 0)
                return ("端口号必须大于0！", null);
            if (string.IsNullOrEmpty(input_user.Text))
                return ("用户名不能为空！", null);
            if (string.IsNullOrEmpty(input_password.Text))
                return ("密码不能为空！", null);
            var entity = new DbConnectionEntity()
            {
                Id = Id,
                Name = input_name.Text.Trim(),
                DbType = (DbType)select_dbType.SelectedIndex,
                IPAddress = input_ipAddress.Text.Trim(),
                Port = (int)inputNumber_port.Value,
                User = input_user.Text.Trim(),
                Password = input_password.Text.Trim(),
                DefaultDbName = string.IsNullOrEmpty(input_defaultDbName.Text) ? string.Empty : input_defaultDbName.Text.Trim()
            };
            return (string.Empty, entity);
        }

        private void select_dbType_SelectedIndexChanged(object sender, IntEventArgs e)
        {
            switch ((DbType)e.Value)
            {
                case Entities.DbType.MySQL:
                    inputNumber_port.InvokeIfRequired(() =>
                    {
                        inputNumber_port.Value = 3306;
                    });
                    break;

                case Entities.DbType.SQLServer:
                    inputNumber_port.InvokeIfRequired(() =>
                    {
                        inputNumber_port.Value = 1433;
                    });
                    break;

                default:
                    break;
            }
        }
    }
}